import collections

import importlib
from actions.action import Action
from logger import logger
import hashlib
import re


def md5(data):
    if isinstance(data, str):
        data = data.encode()
    return hashlib.md5(data).hexdigest()


#
# def walk_element(elements: dict, dump: dict, parent=None):
#     element = Element(parent, dump["payload"])
#     elements[element.key()] = element
#     if "children" in dump:
#         for data in dump["children"]:
#             walk_element(elements, data, element)


def remove_clicked_item(clicked, normal_dict: dict, value=1):
    # 移除已经被点击过的控件
    for key in set(clicked) & set(normal_dict):

        if callable(value):
            v = value(normal_dict[key])
        else:
            v = value

        if clicked[key] >= v:
            normal_dict.pop(key)


def remove_the_same_element(a: dict, b: dict):
    # 从a中，移除ab相同的元素
    l = []
    for key in set(a) & set(b):
        a.pop(key)
        l.append(key)
    return l


def select_element_for_dict(elements: dict, first_list: list):
    """
    筛选符合条件的控件， elements是已经经过初步筛选后的dict

    :param elements: {k:{k1:V1}}
    :param first_list:[{k:v}]
    :return:
    """
    temp = collections.OrderedDict()
    for element_key, element_value in elements.items():
        # 每一个元素
        out_flag = False

        for line in first_list:
            flag = True
            # 每一栏筛选对象
            for k, v in line.items():
                if v != element_value.get(k, ""):
                    flag = False
                    break
            if flag:
                out_flag = True
                break

        if out_flag:
            temp[element_key] = element_value

    return temp


def from_element_creat_key(element: dict):
    return (
        element.get("type", ""),
        element.get("name", ""),
        element.get("text", ""),
        element.get("zOrders", {}).get("global", 0),
        element.get("zOrders", {}).get("local", 0),
    )


def get_item(element_dict: dict, counter_dict: dict = None):
    # 获取字典中，第一个对象
    for element_key, element_value in element_dict.items():
        if counter_dict is not None:
            counter_dict[element_key] = counter_dict.get(element_key, 0) + 1
            logger.info("element_key: {}".format(element_key))
            logger.info("element_count: {}".format(counter_dict[element_key]))
            logger.info("element_value: {} {}".format(element_value, element_value.path))

        return element_value
    return None


def load_action_from_module(module_path):
    try:
        module = importlib.import_module(module_path)
        for cls_name in dir(module):
            if re.match(".+Action", cls_name):
                cls = getattr(module, cls_name)
                if issubclass(cls, Action):
                    return cls
    except ModuleNotFoundError as e:
        return None


def load_actions(modules):
    l = []
    for module in modules:
        action = load_action_from_module(module)
        if action is not None:
            l.append(action())
    return l
